package com.vichat.task;

import com.jcraft.jsch.ChannelSftp;
import com.vichat.common.util.DateUtil;
import com.vichat.common.util.FileTypeUtil;
import com.vichat.common.util.NumberUtils;
import com.vichat.common.util.SFtpUtil;
import com.vichat.res.entity.FtpConfig;
import com.vichat.res.service.ICfgService;
import com.vichat.res.service.IResService;
import com.vichat.res.vo.RecFileVO;
import com.vichat.task.service.ITask;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * Created by wangluyin on 2017/9/6.
 * 该任务是为了单机运行时，清理redis中的频道事件，防止redis内存溢出，1个小时执行一次即可
 */
@Component("RoomUserRecFileScanTask")
public class RoomUserRecFileScanTask implements ITask {
    private static transient final Logger logger = LoggerFactory.getLogger(RoomUserRecFileScanTask.class);

    @Autowired
    ICfgService cfgService;
    @Autowired
    IResService resService;

    @Override
    public String doTask(long cfgTaskId) throws Exception {
        List<FtpConfig> ftpConfigs = cfgService.queryFtpConfig();
        for (FtpConfig ftp : ftpConfigs) {
            if("127.0.0.1".equals(ftp.getFtpIp()) || "localhost".equals(ftp.getFtpIp())){
                scanLocal(ftp);
            }else  if("aliyunoss".equals(ftp.getFtpIp())){
                //skip
            } else{
                scanFtp(ftp);
            }
        }
        return "success";
    }




    public void scanFtp(FtpConfig ftp) {
        try {

            List<RecFileVO> mp4Files = new ArrayList<RecFileVO>();
            List<RecFileVO> mp3Files = new ArrayList<RecFileVO>();
            SFtpUtil sFtpUtil = null;
            try {
                sFtpUtil = new SFtpUtil();
                sFtpUtil.connect(ftp.getFtpIp(), ftp.getFtpName(), ftp.getFtpPass());
                logger.debug("sftp连接成功，开始获取ftp本地目录数据");
                Vector list = sFtpUtil.list(ftp.getLocalPath());
                for (Object obj : list) {
                    ChannelSftp.LsEntry lsEntry = (ChannelSftp.LsEntry) obj;
                    String fileName = lsEntry.getFilename();
                    String longName = lsEntry.getLongname();
                    long fileSize = lsEntry.getAttrs().getSize();
                    //video_recd_30000000_300000002__20170317155914_finish.mp4
                    //video_recd_30000000_300000002__20170317155914_finish.jpg
                    if (StringUtils.startsWith(longName, "-") && StringUtils.startsWithIgnoreCase(fileName, "video_recd") && StringUtils.endsWithIgnoreCase(fileName, "finish.mp4") && fileSize > 0) {//是普通文件，且文件不是空文件
                        logger.debug("filename:" + fileName);
                        RecFileVO recFile = getMp4RecFile(fileName);
                        if (recFile != null) {
                            recFile.setFileSize(fileSize);
                            //jpg图片处理
                            String jpgFileName = FileTypeUtil.getFileNameNoEx(fileName) + ".jpg";
                            for (Object jpgObj : list) {
                                ChannelSftp.LsEntry jpgLsEntry = (ChannelSftp.LsEntry) jpgObj;
                                String name = jpgLsEntry.getFilename();
                                if (StringUtils.equals(name, jpgFileName)) {
                                    recFile.setPicFileName(jpgFileName);
                                }
                            }
                            mp4Files.add(recFile);
                        }
                    }

                    if (StringUtils.startsWith(longName, "-") && StringUtils.startsWithIgnoreCase(fileName, "audio_recd") && StringUtils.endsWithIgnoreCase(fileName, "finish.mp3") && fileSize > 0) {//是普通文件，且文件不是空文件
                        logger.debug("filename:" + fileName);
                        RecFileVO recFile = getMp3RecFile(fileName);
                        if (recFile != null) {
                            recFile.setFileSize(fileSize);
                            mp3Files.add(recFile);
                        }
                    }


                }

                for (RecFileVO mp4File : mp4Files) {
                    try {
                        if (mp4File != null) {//不为null,说明解析成功
                            mp4File.setUrl(ftp.getFtpUrl());
                            sFtpUtil.mkdirs(ftp.getRemotePath() + mp4File.getDir());
                            resService.addRoomResource(mp4File);


                            sFtpUtil.mv(ftp.getLocalPath(), mp4File.getFileName(), ftp.getRemotePath() + mp4File.getDir(), mp4File.getFileName());//迁移到nginx的recd目录
                            if (StringUtils.isNotBlank(mp4File.getPicFileName())) {
                                sFtpUtil.mv(ftp.getLocalPath(), mp4File.getPicFileName(), ftp.getRemotePath() + mp4File.getDir(), mp4File.getPicFileName());//迁移到nginx的recd目录
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("录制文件扫描进程处理出错,错误文件:" + mp4File.getFileName(), e);
                    }
                }

                for (RecFileVO mp3File : mp3Files) {
                    try {
                        if (mp3File != null) {//不为null,说明解析成功
                            mp3File.setUrl(ftp.getFtpUrl());
                            sFtpUtil.mkdirs(ftp.getRemotePath() + mp3File.getDir());
                            resService.addRoomResource(mp3File);
                            sFtpUtil.mv(ftp.getLocalPath(), mp3File.getFileName(), ftp.getRemotePath() + mp3File.getDir(), mp3File.getFileName());//迁移到nginx的recd目录
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("录制文件扫描进程处理出错,错误文件:" + mp3File.getFileName(), e);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                logger.error("录制文件扫描进程处理出错", e);
            } finally {
                if (sFtpUtil != null) {
                    sFtpUtil.close();
                    sFtpUtil = null;
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }

    }


    public void scanLocal(FtpConfig ftp) {
        try {

            List<RecFileVO> mp4Files = new ArrayList<RecFileVO>();
            List<RecFileVO> mp3Files = new ArrayList<RecFileVO>();

            try {

                logger.debug("开始获取服务器本地目录数据");
                File fileFolder = new File(ftp.getLocalPath());
                File[] files;
                if(fileFolder.isDirectory()){
                    files = fileFolder.listFiles();

                }else{
                    throw new Exception(ftp.getLocalPath()+ " is not Directory");
                }


                for (File file : files) {
                    String fileName = file.getName();
                    String longName = file.getAbsolutePath();
                    long fileSize = file.length();
                    //video_recd_30000000_300000002__20170317155914_finish.mp4
                    //video_recd_30000000_300000002__20170317155914_finish.jpg
                    if (StringUtils.startsWithIgnoreCase(fileName, "video_recd") && StringUtils.endsWithIgnoreCase(fileName, "finish.mp4") && fileSize > 0) {//是普通文件，且文件不是空文件
                        logger.debug("filename:" + fileName);
                        RecFileVO recFile = getMp4RecFile(fileName);
                        if (recFile != null) {
                            recFile.setFileSize(fileSize);
                            //jpg图片处理
                            String jpgFileName = FileTypeUtil.getFileNameNoEx(fileName) + ".jpg";
                            for (File jgpFile : files) {
                                String name = jgpFile.getName();
                                if (StringUtils.equals(name, jpgFileName)) {
                                    recFile.setPicFileName(jpgFileName);
                                }
                            }
                            mp4Files.add(recFile);
                        }
                    }

                    if ( StringUtils.startsWithIgnoreCase(fileName, "audio_recd") && StringUtils.endsWithIgnoreCase(fileName, "finish.mp3") && fileSize > 0) {//是普通文件，且文件不是空文件
                        logger.debug("filename:" + fileName);
                        RecFileVO recFile = getMp3RecFile(fileName);
                        if (recFile != null) {
                            recFile.setFileSize(fileSize);
                            mp3Files.add(recFile);
                        }
                    }


                }

                for (RecFileVO mp4File : mp4Files) {
                    try {
                        if (mp4File != null) {//不为null,说明解析成功
                            mp4File.setUrl(ftp.getFtpUrl());
                            resService.addRoomResource(mp4File);
                            File sourceMP4 = new File(ftp.getLocalPath() + "/"+mp4File.getFileName());

                            mkdirs(ftp.getRemotePath() + mp4File.getDir());

                            File destMP4 = new File(ftp.getRemotePath() + mp4File.getDir()+ "/"+mp4File.getFileName());
                            sourceMP4.renameTo(destMP4);//迁移到nginx的recd目录
                            if (StringUtils.isNotBlank(mp4File.getPicFileName())) {
                                File sourceJPG = new File(ftp.getLocalPath() + "/"+mp4File.getPicFileName());//迁移到nginx的recd目录 JPG
                                File destJPG = new File(ftp.getRemotePath() + mp4File.getDir()+ "/"+mp4File.getPicFileName());
                                sourceJPG.renameTo(destJPG);//迁移到nginx的recd目录
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("录制文件扫描进程处理出错,错误文件:" + mp4File.getFileName(), e);
                    }
                }

                for (RecFileVO mp3File : mp3Files) {
                    try {
                        if (mp3File != null) {//不为null,说明解析成功
                            mp3File.setUrl(ftp.getFtpUrl());
                            resService.addRoomResource(mp3File);
                            File sourceMP3 = new File(ftp.getLocalPath() + "/"+mp3File.getFileName());//迁移到nginx的recd目录 MP3

                            mkdirs(ftp.getRemotePath() + mp3File.getDir());

                            File destMP3 = new File(ftp.getRemotePath() + mp3File.getDir()+ "/"+mp3File.getFileName());
                            sourceMP3.renameTo(destMP3);//迁移到nginx的recd目录

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("录制文件扫描进程处理出错,错误文件:" + mp3File.getFileName(), e);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                logger.error("录制文件扫描进程处理出错", e);
            } finally {

            }

        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }

    }

    static void mkdirs(String dirPath){
        try {
            File dir =   new File(dirPath);
            if(!dir.exists()){
                dir.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("创建文件夹目录出错", e);
        }


    }



    /**
     * 命名规则 video_recd_{rid}_{uid}_{refid}_{yyyyMMddhhmmss}_finish.mp4
     * For example：video_recd_30000000_300000002__20170317155914_finish.mp4
     * @param fileName
     * @return
     */
    static  RecFileVO getMp4RecFile(String fileName) {
        RecFileVO recFile = null;
        String fileNameNoEx = FileTypeUtil.getFileNameNoEx(fileName);
        String[] strs = StringUtils.splitPreserveAllTokens(fileNameNoEx, "_");//strs[0]=video;strs[1]=recd;strs[2]={rid};strs[3]={uid};strs[4]={refid};strs[5]={yyyyMMddhhmmss};
        if (strs != null && strs.length > 5) {
            long rid = NumberUtils.toLong(strs[2], -1);
            long uid = NumberUtils.toLong(strs[3], -1);
            String recdTime = strs[5];
            if (rid > 0 && uid > 0 ) {
                recFile = new RecFileVO();
                recFile.setRid(rid);
                recFile.setUid(uid);
                recFile.setFileName(fileName);
                recFile.setRecdTime(recdTime);
                recFile.setDir(DateUtil.getToday("yyyyMMdd"));
            }
        }
        return recFile;
    }

    /**
     * 命名规则 audio_recd_{rid}_{uid}_{refid}_{yyyyMMddhhmmss}_finish.mp4
     * For example：audio_recd_30000000_300000002__20170317155914_finish.mp4
     * @param fileName
     * @return
     */
    static  RecFileVO getMp3RecFile(String fileName) {
        RecFileVO recFile = null;
        String fileNameNoEx = FileTypeUtil.getFileNameNoEx(fileName);
        String[] strs = StringUtils.splitPreserveAllTokens(fileNameNoEx, "_");//strs[0]=video;strs[1]=recd;strs[2]={rid};strs[3]={uid};strs[4]={refid};strs[5]={yyyyMMddhhmmss};
        if (strs != null && strs.length > 5) {
            long rid = NumberUtils.toLong(strs[2], -1);
            long uid = NumberUtils.toLong(strs[3], -1);
            String recdTime = strs[5];
            if (rid > 0 && uid > 0 ) {
                recFile = new RecFileVO();
                recFile.setRid(rid);
                recFile.setUid(uid);
                recFile.setFileName(fileName);
                recFile.setRecdTime(recdTime);
                recFile.setDir(DateUtil.getToday("yyyyMMdd"));
            }
        }
        return recFile;
    }


}
